﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using AutoMapper;
using Huirui.Cavan.Application.MainBoundedContext.PurchaseModule;
using Huirui.Cavan.Domain.MainBoundedContext.PurchaseModule;
using Huirui.Cavan.Domain.MainBoundedContext.ReportModule;
using Huirui.Cavan.Domain.MainBoundedContext.SearchModule;
using Huirui.Cavan.Presentation.Seedwork;
using Huirui.Cavan.Presentation.ViewModel.PurchaseModule;
using Huirui.Cavan.Core.Extension;
using Huirui.Cavan.Application.MainBoundedContext.SystemModule;
using Huirui.Cavan.Domain.Seedwork;
using Newtonsoft.Json;
using Huirui.Cavan.Domain.MainBoundedContext.SystemModule;

namespace Huirui.Cavan.Presentation.Controller.PurchaseModule
{
    public class PayController : EntityController<Pay, string, PaySearch, IPayViewModel, IPayAppService>, IPayController
    {
        private ICurrencyAppService CurrencyAppService { get; set; }

        public override string ControllerName
        {
            get { return ControllerConst.PAY; }
        }

        public override bool UseDenied
        {
            get { return false; }
        }

        public PayController()
        {
            this.Model = ModelFactory.CreateModel<IPayViewModel>();
        }

        [ActionName(ActionConst.LIST)]
        [ActionPermissionAttribute(Name = "pay_query")]
        public JsonResult GetPays(string payCode, DateTime? startDate, DateTime? endDate, string supplierCode)
        {
            PayJsonViewModel json = new PayJsonViewModel();
            json.rows = new List<PayJson>();

            IList<Pay> pays = this.AppService.GetBySearch(SearchFactory.CreatePaySearch(payCode, startDate, endDate, supplierCode)).ToList();
            foreach (Pay p in pays)
            {
                PayJson unpj = Mapper.Map<Pay, PayJson>(p);
                json.rows.Add(unpj);
            }
            json.total = pays.Count;

            return Json(json, "application/json");
        }

        [ActionName("uppr")]
        public JsonResult GetUnPayAndPayReport(DateTime? startDate, DateTime? endDate, string supplierCode)
        {
            UnPayAndPayReportViewModel json = new UnPayAndPayReportViewModel();
            json.rows = new List<UnPayAndPayReport>();

            IList<UnPayAndPayReport> unPayAndPayReports = this.AppService.GetUnPayAndPayReport(startDate, endDate, supplierCode, 10, 1);
            foreach (UnPayAndPayReport r in unPayAndPayReports)
            {
                json.rows.Add(r);
            }
            json.total = unPayAndPayReports.Count;

            return Json(json, "application/json");
        }

        [ActionName(ActionConst.ADD)]
        [HttpGet]
        [ActionPermissionAttribute(Name = "pay_query")]
        public ActionResult AddPay(string id)
        {
            if (id.IsNotEmpty())
            {
                this.Model.Item = this.AppService.GetById(id);
                this.Model.UnPaid = this.Model.Item.Amount - this.Model.Item.PayDetails.Sum(pd => pd.Amount);
            }
            else
            {
                this.Model.Item.FromAccount = new Account();
                this.Model.Item.Currency = "CNY";
            }
            IList<Currency> currencies = this.CurrencyAppService.GetBySearch(new CurrencySearch()).ToList();
            this.Model.Currencies.Add(new SelectListItem() { Text = "请选择", Value = "1" });
            currencies.ForEach(c =>
            {
                this.Model.Currencies.Add(new SelectListItem() { Text = c.Code, Value = c.Rate.ToString() });
                if (id.IsEmpty() && c.IsLocal)
                {
                    this.Model.Currencies.FirstOrDefault(c1 => c1.Text == c.Code).Selected = true;
                    this.Model.Item.CurrencyRate = c.Rate;
                }
            });

            if (id.IsNotEmpty())
            {
                this.Model.Currencies.FirstOrDefault(c1 => c1.Text == this.Model.Item.Currency).Selected = true;
            }
            return View("~/Views/Purchase/v1/addPay.cshtml", this.Model);
        }

        [ActionName(ActionConst.ADD)]
        [HttpPost]
        [ActionPermissionAttribute(Name = "pay_edit")]
        public JsonResult AddPay(PayViewModel model)
        {
            BoolResult jsonResult = null;
            model.Item.PayDetails = JsonConvert.DeserializeObject<IList<PayDetail>>(model.PayDetails);

            BoolGenericResult<Pay> result = this.AppService.AddOrUpdate(model.Item);
            jsonResult = new BoolResult(result.IsSuccess, result.Messages);

            return Json(jsonResult, "application/json");
        }

        [ActionName(ActionConst.LIST)]
        [HttpGet]
        public ActionResult GetPays()
        {
            return View("~/Views/Purchase/v1/payList.cshtml");
        }

        [ActionName(ActionConst.SEARCH)]
        [HttpPost]
        public JsonResult GetPays(PayViewModel model)
        {
            PayJsonViewModel json = new PayJsonViewModel();
            json.rows = new List<PayJson>();

            long total = 0;
            IList<Pay> pays = this.AppService.GetBySearch(new PaySearch()
            {
                StartDate = model.SearchParam.StartDate,
                EndDate = model.SearchParam.EndDate,
                SupplierCode = model.SearchParam.SupplierCode,
                ID = model.SearchParam.ID
            }, out total).ToList();
            foreach (Pay p in pays)
            {
                PayJson cj = Mapper.Map<Pay, PayJson>(p);
                json.rows.Add(cj);
            }
            json.total = total;

            return Json(json, "application/json");
        }

        [ActionName("paid")]
        public JsonResult GetPaid(string id)
        {
            UnPayJsonViewModel json = new UnPayJsonViewModel();
            json.rows = new List<UnPayJson>();
            json.total = 0;
            if (id.IsNotEmpty())
            {
                IList<UnPay> unPays = new List<UnPay>();
                Pay pay = this.AppService.GetById(id);
                pay.PayDetails.ForEach(pd =>
                {
                    unPays.Add(pd.UnPay);
                });
                foreach (UnPay unp in unPays)
                {
                    UnPayJson unpj = Mapper.Map<UnPay, UnPayJson>(unp);
                    unpj.Amount = pay.PayDetails.FirstOrDefault(pd => pd.UnPay.Id == unp.Id).Amount;
                    json.rows.Add(unpj);
                }
                json.total = unPays.Count;
            }

            return Json(json, "application/json");
        }
    }
}
